package com.xiaoma.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoma.config.AlipayTemplate;
import com.xiaoma.entity.PayAsyncVo;
import com.xiaoma.entity.PayVo;
import com.xiaoma.service.OrderService;
import entity.Payorder;
import entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * @Author: xiaoma
 * @Date: 2021/7/16 10:26
 * @description:
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;
    @GetMapping("/createOrder/{id}/{token}")
    public String createOrder(@PathVariable("id") Integer id,@PathVariable("token")String token, HttpServletRequest request) throws AlipayApiException {
        String uid = JwtUtils.getMemberIdByJwtToken(request);
        //        Payorder order = orderService.getOne(new QueryWrapper<Payorder>().eq("uid", user.getId()).eq("gid", id));
        return   orderService.createOrder(uid, id.toString(), token);
    }

    @PostMapping("/payed/notify")
    public String handlerAlipay(HttpServletRequest request, PayAsyncVo payAsyncVo) throws AlipayApiException {
        System.out.println("收到支付宝异步通知******************");
        // 只要收到支付宝的异步通知，返回 success 支付宝便不再通知
        // 获取支付宝POST过来反馈信息
        //  TODO 需要验签
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
        ReentrantLock reentrantLock = new ReentrantLock();
        if (signVerified) {
            System.out.println("支付宝异步通知验签成功");
            //修改订单状态
            String id = request.getParameter("out_trade_no");
            Payorder payorder = new Payorder();
            payorder.setId(id); 
            payorder.setOrderStatus(2);
            orderService.updateById(payorder);
            log.info("订单状态修改完成");
            return "success";
        } else {
            System.out.println("支付宝异步通知验签失败");
            return "error";
        }

    }
    @GetMapping("/queryById/{id}")
    public Payorder queryById(@PathVariable String id){
       return orderService.getById(id);
    }
}
